package com.spica.spicaschool.ui.login

import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.lifecycle.rxLifeScope
import com.kongzue.dialogx.dialogs.FullScreenDialog
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.spica.spicaschool.ContentActivity
import com.spica.spicaschool.R
import com.spica.spicaschool.base.BindingActivity
import com.spica.spicaschool.bean.login.LoginBean
import com.spica.spicaschool.databinding.ActivityLoginBinding
import com.spica.spicaschool.databinding.LayoutFullPhoneLoginBinding
import com.spica.spicaschool.network.Url
import com.spica.spicaschool.utils.*
import com.zackratos.ultimatebarx.ultimatebarx.UltimateBarX
import rxhttp.toStr
import rxhttp.wrapper.param.RxHttp
import java.util.regex.Pattern


/**
 * 登录
 */
@Suppress("LABEL_NAME_CLASH")
class LoginActivity : BindingActivity<ActivityLoginBinding>() {


  private lateinit var dialogBinding: LayoutFullPhoneLoginBinding


  override fun initializer() {
    UltimateBarX.with(this).transparent().applyStatusBar()
    viewBinding.btnLogin.setOnClickListener {
      FullScreenDialog.show(object :
        OnBindView<FullScreenDialog?>(R.layout.layout_full_phone_login) {
        override fun onBind(dialog: FullScreenDialog?, view: View) {
          dialogBinding = LayoutFullPhoneLoginBinding.bind(view)
          if (dialog != null) {
            initFullScreenLoginDialog(dialog)
          }
        }
      })
    }
  }

  //初始化登录弹窗
  private fun initFullScreenLoginDialog(fullScreenDialog: FullScreenDialog) {
    dialogBinding.btnCancel.setOnClickListener { fullScreenDialog.dismiss() }
    dialogBinding.btnCancel.text = "取消"
    dialogBinding.btnSubmit.text = "下一步"
    dialogBinding.btnSubmit.setOnClickListener(View.OnClickListener {
      if ((dialogBinding.etUserName.text.toString().trim().isEmpty())) {
        TipDialog.show("请输入账号", WaitDialog.TYPE.WARNING)
        return@OnClickListener
      }
      if (isPhoneNum(dialogBinding.etVCode.text.toString())) {
        TipDialog.show("手机号码格式不正确", WaitDialog.TYPE.WARNING)
        return@OnClickListener
      }
      if (dialogBinding.btnSubmit.text == "下一步") {
        sendSms()
        KeyBoardUtils.closeKeybord(dialogBinding.etUserName, this)
      }
      dialogBinding.boxUserName.animate().x(-getDisplayWidth().toFloat()).duration = 300
      dialogBinding.boxVCode.x = getDisplayWidth().toFloat()
      dialogBinding.boxVCode.visibility = View.VISIBLE
      dialogBinding.boxVCode.animate().x(0F).duration = 300
      dialogBinding.etVCode.isFocusable = true
      dialogBinding.etVCode.requestFocus()
      dialogBinding.btnCancel.text = "上一步"
      dialogBinding.btnCancel.setOnClickListener {
        dialogBinding.boxUserName.animate().x(0F).duration = 300
        dialogBinding.boxVCode.animate().x(getDisplayWidth().toFloat()).duration = 300
        dialogBinding.etUserName.isFocusable = true
        dialogBinding.etUserName.requestFocus()
        initFullScreenLoginDialog(fullScreenDialog)
      }
      dialogBinding.btnSubmit.text = "登录"
      dialogBinding.btnSubmit.setOnClickListener(View.OnClickListener {

        if ((dialogBinding.etVCode.text.toString().trim().isEmpty())) {
          TipDialog.show("请输入验证码", WaitDialog.TYPE.WARNING)
          return@OnClickListener
        }
        WaitDialog.show("登录中...")
        checkCode()
      })
    })
  }

  /**
   * 获取屏幕宽度
   */
  private fun getDisplayWidth(): Int {
    return resources.displayMetrics.widthPixels
  }

  /**
   * 判断手机号
   */
  private fun isPhoneNum(phone: String): Boolean {
    Log.e("手机号：", phone)
    val compile = Pattern.compile("^(13|14|15|16|17|18|19)\\d{9}$")
    val matcher = compile.matcher(phone)
    return matcher.matches()
  }

  // 发送验证短信
  private fun sendSms() {
    rxLifeScope.launch(
      {
        val res = RxHttp
          .postForm(Url.SEND_SMS_TEST)
          .add("phone", dialogBinding.etUserName.text.toString())
          .toStr()
          .await()
        Log.e("发送短信", res)
      },
      {
        Toast.makeText(this, it.message.toString(), Toast.LENGTH_SHORT).show()
      }
    )
  }

  private fun checkCode() {
    if (dialogBinding.etVCode.text.toString().length != 6) {
      TipDialog.show("验证码错误", WaitDialog.TYPE.WARNING)
      return
    }
    // 输入完成时候发送验证请求
    RxHttp.postForm(Url.LOGIN)
      .add("phone", dialogBinding.etUserName.text.toString()) // 电话
      .add("code", dialogBinding.etVCode.text.toString()) // 验证码
      .asResponseList(LoginBean::class.java) // 返回验证完毕获取data
      .subscribe({
        SpUtils.putSpValue(
          context = this@LoginActivity,
          key = TOKEN_SIGN,
          value = it[0].token
        )
        startActivity(Intent(this@LoginActivity, ContentActivity::class.java))
        finish()
        UiUtils.doMainThreadle({
          WaitDialog.dismiss()
        }, 200)

      }, {
        WaitDialog.dismiss()
        TipDialog.show("验证码错误", WaitDialog.TYPE.WARNING)
      })
  }


  override fun setupViewBinding(inflater: LayoutInflater): ActivityLoginBinding =
    ActivityLoginBinding.inflate(inflater)
}
